import React, { useRef, useState } from 'react';
import { PlusOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Avatar, Switch, message, Modal, Form } from 'antd';
import ProTable from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import { getUsers, lockUser, createUser, UpdateUser } from '@/services/ant-design-pro/api';
import ProForm, { ProFormText } from '@ant-design/pro-form';
export default () => {
  const actionRef = useRef();

  const [isModalVisible, setisModalVisible] = useState(false);
  const [isModalVisibleEdit, setisModalVisibleEdit] = useState(false);
  const ChangModel = (name) => {
    if (name == 'edit') {
      setisModalVisibleEdit(!isModalVisibleEdit);
    } else {
      setisModalVisible(!isModalVisible);
    }
  };
  const getData = async (params) => {
    const response = await getUsers(params);

    return {
      data: response.data,
      success: true,
      total: response.meta.pagination.total_pages,
    };
  };
  const [form] = Form.useForm();
  const columns = [
    {
      title: '头像',
      dataIndex: 'avatar_url',
      hideInSearch: true,
      render: (_, record) => <Avatar size={32} src={record.avatar_url} icon={<UserOutlined />} />,
    },
    {
      title: '昵称',
      dataIndex: 'name',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      copyable: true,
    },
    {
      title: '是否禁用',
      dataIndex: 'is_locked',
      hideInSearch: true,
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.is_locked === 0}
          onChange={async () => {
            const respnse = await lockUser(record.id);
            if (respnse.status === undefined) {
              message.success('操作成功');
            } else {
              message.error('操作失败');
            }
          }}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            ChangModel('edit');
            form.setFieldsValue({
              id: record.id,
              name: record.name,
              email: record.email,
            });
          }}
        >
          编辑
        </a>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}, sort, filter) => getData(params)}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        headerTitle="用户列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              ChangModel();
            }}
          >
            新建
          </Button>,
        ]}
      />
      <Modal title="添加用户" visible={isModalVisible} onCancel={ChangModel} footer={null}>
        <ProForm
          onFinish={async (values) => {
            const response = await createUser(values);
            if (response.status === undefined) {
              message.success('添加成功');
              ChangModel();
              actionRef.current.reload();
              return true;
            } else if (response.status === 422) {
              let msg = '';
              console.log(response.errors);
              for (const key in response.errors) {
                msg += response.errors[key][0];
              }
              message.error(msg);
            }
            console.log(values);
          }}
        >
          <ProFormText
            name="name"
            label="昵称"
            placeholder="请输入昵称"
            rules={[
              { required: true, message: '请输入昵称' },
              { max: 16, message: '昵称最长十六位字母或八位文字' },
            ]}
          />
          <ProFormText
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' },
            ]}
          />
          <ProFormText.Password
            name="password"
            label="密码"
            placeholder="请输入密码"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码最少六位' },
            ]}
          />
        </ProForm>
      </Modal>
      <Modal
        title="添加用户"
        visible={isModalVisibleEdit}
        onCancel={() => ChangModel('edit')}
        footer={null}
      >
        <ProForm
          form={form}
          onFinish={async (values) => {
            console.log(values);
            const response = await UpdateUser(values.id, values);
            if (response.status === undefined) {
              message.success('修改成功');
              ChangModel('edit');
              actionRef.current.reload();
              return true;
            } else if (response.status === 422) {
              let msg = '';
              console.log(response.errors);
              for (const key in response.errors) {
                msg += response.errors[key][0];
              }
              message.error(msg);
            }
          }}
        >
          <ProFormText
            name="name"
            label="昵称"
            placeholder="请输入昵称"
            rules={[
              { required: true, message: '请输入昵称' },
              { max: 16, message: '昵称最长十六位字母或八位文字' },
            ]}
          />
          <ProFormText
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' },
            ]}
          />
          <ProFormText name="id" hidden="true" />
        </ProForm>
      </Modal>
    </PageContainer>
  );
};
